package hong.jun.pet_home.controller.pet;

import hong.jun.basic.util.AjaxResult;
import hong.jun.basic.util.PageList;
import hong.jun.pet_home.domain.pet.Pet;
import hong.jun.pet_home.query.PetQuery;
import hong.jun.pet_home.service.pet.IPetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * restfull风格
 *
 * @Controller
 * @ResponseBody
 */

@RestController
@RequestMapping("/pet")
public class PetController {

    @Autowired
    private IPetService petService;

    /**
     * 判断有无id决定新增还是修改
     */
    @PutMapping
    public AjaxResult saveOrUpdate(@RequestBody Pet pet) {
        try {
            if (pet.getId() != null) {
                petService.update(pet);
            } else {
                petService.save(pet);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.toString());
        }
    }

    /**
     * 上架
     */
    @PutMapping("/on_shelf")
    public AjaxResult on_shelf(@RequestBody Pet pet) {
        try {
            petService.on_shelf(pet);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.toString());
        }
    }

    /**
     * 根据id 删除
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult del(@PathVariable("id") Long id) {
        try {
            petService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.toString());
        }
    }

    /**
     * 根据id 批量删除
     */
    @PostMapping("/dels")
    public AjaxResult dels(@RequestBody Long[] ids) {
        try {
            //System.out.println(ids.toString());
            petService.deletes(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.toString());
        }
    }

    /**
     * 根据Id查询
     */
    @GetMapping(value = "/{id}")
    public Pet getById(@PathVariable("id") Long id) {
        return petService.getById(id);
    }

    /**
     * 查询上架的全部商品
     */
    @PostMapping("/getAll")
    public List<Pet> getAll() {
        return petService.getAll();
    }

    /**
     * 条件分页查询
     */
    @PostMapping
    public PageList<Pet> getPage(@RequestBody PetQuery query) {
        System.out.println("条件" + query);
        return petService.queryPage(query);
    }
}
